import questionApi from "../../../apis/rc/question.mjs";

import QuestionShow from "../../components/question-base/question-show/index.vue";
import BaseShow from "./components/base-show.vue";
import TagShow from "./components/tag-show.vue";
import TypeNav from "./components/type-nav.vue";
import QuestionNav from "./components/question-nav.vue";
import EditDialog from "./components/edit-dialog.vue";

import lifeMixin from "./life.mjs";
import dataMixin from "./data.mjs";

let scrollTimer = null;

export default {
	name: "preview-page",
	mixins: [lifeMixin, dataMixin],
	components: {
		QuestionShow,
		BaseShow,
		TagShow,
		TypeNav,
		QuestionNav,
		EditDialog
	},
	methods: {
		// 关闭页面
		closePage() {
			window.close();
		},
		// 根据当前的情况计算顶部类型导航的选中状态,注意：该函数必须在节点更新完成后执行
		computeActiveType() {
			// 单位时间内只执行最后一次触发的该函数，避免滚动事件频繁触发，优化性能
			clearTimeout(scrollTimer);
			scrollTimer = setTimeout(() => {
				const boxScrollTop = document.getElementById("question-scroll-box").scrollTop;
				const titles = this.$refs.questionTypeTitle;
				if (titles.length > 1) {
					const index = titles.findIndex((i) => boxScrollTop < i.offsetTop);
					if (index === -1) {
						this.activeType = titles[titles.length - 1].getAttribute("data-type");
					} else {
						this.activeType = titles[index - 1].getAttribute("data-type");
					}
				} else {
					this.activeType = titles[0].getAttribute("data-type");
				}
			}, 20);
		},
		// 点击试题类型导航
		async clickNavType(item) {
			// 寻找选中类型的第一题是否在当前页面中
			const findIndex = this.pageArrQuestionAllList.findIndex((i1) => i1.some((i2) => i2.questionType === item.questionType));
			if (this.page.pageIndex !== findIndex + 1) {
				// 不在当前页面中，则先跳到对应页面
				this.page.pageIndex = findIndex + 1;
				await this.updateQuestionShowList();
			}
			// 翻页完成，滚动到选中的题号位置
			const navId = this.questionShowList.find((i) => i.questionType === item.questionType).navId;
			this.$nextTick(() => {
				this.scrollQuestionList("q-" + navId);
				// 点击时强制让点击按钮变为选中状态，为了避免滚动监听覆盖状态，加个延时器，在监听后执行
				setTimeout(() => {
					this.activeType = item.questionType;
				}, 40);
			});
		},
		// 点击试题题号导航
		async clickNavNumber(clickItem, clickItemParent) {
			// 先将所有的选中状态置为未选中
			this.questionNavList.forEach((item1) => {
				item1.questionTypeDataList.forEach((item2) => {
					item2.isChecked = false;
				});
			});
			// 修改点击的选中状态
			clickItem.isChecked = true;
			// 如果选中的题号所属的父题不存在当前页面中，则先跳到对应页面
			if (!this.questionShowList.some((i) => i.parentNavId === clickItem.parentNavId)) {
				const findIndex = this.pageArrQuestionAllList.findIndex((i1) => i1.some((i2) => i2.parentNavId === clickItem.parentNavId));
				this.page.pageIndex = findIndex + 1;
				await this.updateQuestionShowList();
			}
			// 翻页完成，滚动到选中的题号位置
			this.$nextTick(() => {
				let navId = clickItem.navId;
				if (["A", "CF", "L", "C"].includes(clickItemParent.questionType)) {
					let smallNavIndex = clickItem.navId.split("-");
					smallNavIndex = smallNavIndex[smallNavIndex.length - 1];
					if (smallNavIndex === "0") {
						// 如果选中的是复合题，并且是复合题下的第一个小题，那么则滚动到父级题干，而不是小题本身
						navId = clickItem.parentNavId;
					}
				}
				this.scrollQuestionList("q-" + navId);
				// 点击时强制让点击按钮变为选中状态，为了避免滚动监听覆盖状态，加个延时器，在监听后执行
				setTimeout(() => {
					this.activeType = clickItemParent.questionType;
				}, 40);
			});
		},
		// 将试题列表滚动到指定id元素
		scrollQuestionList(navId) {
			const wrap = document.getElementById("question-scroll-box");
			const el = document.getElementById(navId);
			wrap.scrollTo(0, el.offsetTop);
		},
		// 根据当前的分页信息，更新展示的试题列表
		updateQuestionShowList() {
			const list = this.pageArrQuestionAllList[this.page.pageIndex - 1];
			return new Promise((rs) => {
				if (this.dataGetType === "localStorageAll") {
					// 如果是缓存类型，本地数据已足够
					this.questionShowList = list;
					rs();
				} else {
					// 如果是异步类型，根据id列表查询题目列表
					this.isLoading = true;
					questionApi.queryQuestionInfoBatch({
						data: {
							resourceIds: list.map((i) => i.resourceId)
						},
						success: (resData) => {
							// 把查到的数据和缓存的数据进行合并使用
							if (!resData.length === list.length) {
								this.$message.error("获取的试题数量与导航数量不一致");
								return;
							}
							// 将本地导航的数据与获取的试题列表数据进行组合
							this.questionShowList = list.map((item1, index1) => {
								const resDataItem = resData[index1];
								const resDataItemSmallQuestionList = resDataItem.smallQuestionList || []; // 如果没有子题属性，加个空数组，避免数据组合出错
								let resDataItemLabelList = resDataItem.labelList;
								if (["A", "CF", "L", "C"].includes(item1.questionType)) {
									// 复合题，取子题的labelList
									resDataItemLabelList = resDataItemSmallQuestionList[0].labelList;
								}
								// 将父级的标签列表属性整合成一个完整的数据
								const parentLabelList = this.tagOptions.map((item2) => {
									const findLabelItem = resDataItemLabelList.find((item3) => item3.labelId === item2.labelId);
									return {
										labelId: item2.labelId,
										labelName: item2.labelName,
										labelDetailId: findLabelItem ? findLabelItem.labelDetailId : "",
										labelDetailName: findLabelItem ? findLabelItem.labelDetailName : ""
									};
								});
								return {
									...item1,
									...resDataItem,
									labelList: parentLabelList,
									smallQuestionList: item1.smallQuestionList.map((item2, index2) => {
										// 将子级的标签列表属性整合成一个完整的数据
										const childLabelList = this.tagOptions.map((item3) => {
											const findLabelItem = resDataItemSmallQuestionList[index2].labelList.find((item4) => item4.labelId === item3.labelId);
											return {
												labelId: item3.labelId,
												labelName: item3.labelName,
												labelDetailId: findLabelItem ? findLabelItem.labelDetailId : "",
												labelDetailName: findLabelItem ? findLabelItem.labelDetailName : ""
											};
										});
										return {
											...item2,
											...resDataItemSmallQuestionList[index2],
											applicableYear: resDataItem.applicableYear, // 子题继承父级的年份
											areaRelationListResponseVoList: resDataItem.areaRelationListResponseVoList, // 子题继承父级的地区
											optionList: item1.questionType === "C" ? [] : resDataItemSmallQuestionList[index2].optionList,
											labelList: childLabelList
										};
									})
								};
							});
							this.isLoading = false;
							rs();
						}
					});
				}
			});
		},
		// 修改分页信息
		async changePage() {
			await this.updateQuestionShowList();
			document.getElementById("question-scroll-box").scrollTo(0, 0);
		},
		/**
		 * @param {object} dataItem 编辑的试题对象
		 * @param {any} questionType 编辑的试题类型
		 */
		clickEdit(dataItem, questionType) {
			this.editQuestionObject = dataItem;
			this.editQuestionType = questionType;
			this.isShowEditDialog = true;
		},
		/**
		 * @param {object} params 修改的数据参数
		 * @param {object} clickItem 点击的试题对象
		 */
		editSuccess(params, clickItem) {
			this.questionNavList.forEach((item1) => {
				item1.questionTypeDataList.forEach((item2) => {
					if (item2.navId === clickItem.navId || item2.parentNavId === clickItem.navId) {
						item2.isComplete = true;
					}
				});
			});
			// 如果有新值则更新当前的展示数据，没有的还按原来的不变(因为所有选项节课唯恐，注意字符串类型为空时也是有效值)
			clickItem.questionDeveloperId = params.questionDeveloperId === undefined ? clickItem.questionDeveloperId : params.questionDeveloperId;
			clickItem.questionDeveloperName = params.questionDeveloperName === undefined ? clickItem.questionDeveloperName : params.questionDeveloperName;
			clickItem.questionChapterResponseVoList = params.chapterList || clickItem.questionChapterResponseVoList;
			clickItem.questionKnowledgeResponseVoList = params.knowledgeList || clickItem.questionKnowledgeResponseVoList;
			clickItem.applicableYear = params.applicableYear === undefined ? clickItem.applicableYear : params.applicableYear;
			clickItem.areaRelationListResponseVoList = params.areaList || clickItem.areaRelationListResponseVoList;
			// 传来的标签列表可能只包含部分标签，匹配对应的标签进行替换
			clickItem.labelList.forEach((item1) => {
				const findLabel = params.labelList.find((item2) => item2.labelId === item1.labelId);
				if (findLabel) {
					item1.labelDetailId = findLabel.labelDetailId;
					item1.labelDetailName = findLabel.labelDetailName;
				}
			});
			// 如果是复合题题干，则将复合题的年份，地区，试题分类，适用范围同步到子题数据中
			if (this.editQuestionType === "parent") {
				clickItem.smallQuestionList.forEach((item1) => {
					item1.applicableYear = params.applicableYear;
					item1.areaRelationListResponseVoList = params.areaList;
					item1.labelList.forEach((item2) => {
						const findChildLabel = params.labelList.find((item3) => item3.labelId === item2.labelId);
						if (findChildLabel) {
							item2.labelDetailId = findChildLabel.labelDetailId;
							item2.labelDetailName = findChildLabel.labelDetailName;
						}
					});
				});
			}
		}
	}
};
